package com.appbee.core.server.twig;

import java.io.IOException;
import javax.inject.Singleton;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.PreparedQuery;
import com.google.appengine.api.datastore.Query;

@Singleton
public class RenameEntity extends HttpServlet
{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException
	{
		rename(	"com_gband_cm_server_data_NavItem",
				"com_appbee_cm_server_data_NavItem");
		rename(	"com_gband_cm_server_data_ActivityEntry",
				"com_appbee_cm_server_data_ActivityEntry");
		rename(	"com_gband_settings_server_Setting",
				"com_appbee_settings_server_Setting");
		rename(	"com_gband_article_server_Article",
				"com_appbee_article_server_Article");
		rename("com_gband_news_server_News", "com_appbee_news_server_News");
		rename(	"com_gband_songs_server_model_Song",
				"com_appbee_songs_server_model_Song");
		rename(	"com_gband_user_server_model_Member",
				"com_appbee_user_server_model_Member");
		resp.getWriter().println("<p>done</p>");

	}

	private void rename(String oldName, String newName)
	{
		DatastoreService datastore = DatastoreServiceFactory
				.getDatastoreService();
		Query q = new Query(oldName);
		PreparedQuery preparedQuery = datastore.prepare(q);

		for (Entity e : preparedQuery.asIterable())
		{
			Entity newE = new Entity(newName);
			newE.setPropertiesFrom(e);
			datastore.put(newE);
			datastore.delete(e.getKey());
		}
	}

}
